package com.dqhl.stable.listener;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.dqhl.stable.util.Dlog;

/**
 * Created by cheng on 2016/10/12.
 * 光感应监听
 */
public class LightListener implements SensorEventListener {

    private Context context;
    private SensorManager sensorManager; //传感器管理器
    private Sensor sensor; //传感器
    private onLightListener onLightListener;

    /**
     * 设置光感应监听器
     * @param onLightListener
     */
    public void setOnLightListener(LightListener.onLightListener onLightListener) {
        this.onLightListener = onLightListener;
    }

    public LightListener(Context context){
        this.context = context;
        start();
    }

    public void start() {
        // 获取SensorManager对象
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null){
            // 获取Sensor光传感器对象
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        }
        // 注册
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    public void stop(){
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //获取精度
        float acc = sensorEvent.accuracy;
        //获取光线强度
        float lux = sensorEvent.values[0];
//        tv_content.setText("精度acc:" + acc + ";" + "光线强度lux：" + lux);
//        Dlog.e("精度acc:" + acc + ";" + "光线强度lux：" + lux);
        onLightListener.onLight(acc, lux);
//        if (lux > 2000) {
//            tv_have_light.setText("有光照");
//            // TODO 向服务器发送警报
//        } else {
//            tv_have_light.setText("");
//        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    public interface onLightListener{
        void onLight(float acc, float lux);
    }
}
